import { useState, useEffect } from 'react';
import { useTheme } from '../hooks/useTheme';
import { toast } from 'sonner';
import { Send, RefreshCcw, Info, AlertTriangle, Check, X, Code, Server, Settings, Terminal } from 'lucide-react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';

// 类型定义
type Character = 'liuBei' | 'caoCao' | 'sunQuan';

// 调试页面组件
export default function DebugPage() {
  const { theme, isDark } = useTheme();
  const [appInfo, setAppInfo] = useState<Record<string, any>>({});
  const [healthStatus, setHealthStatus] = useState<Record<string, any>>({});
  const [configStatus, setConfigStatus] = useState<Record<string, any>>({});
  const [apiTestMessage, setApiTestMessage] = useState('');
  const [selectedCharacter, setSelectedCharacter] = useState<Character>('liuBei');
  const [isTesting, setIsTesting] = useState(false);
  const [apiResponse, setApiResponse] = useState<string>('');
  const [apiError, setApiError] = useState<string>('');
  const [logs, setLogs] = useState<string[]>([]);
  const [performanceData, setPerformanceData] = useState<Array<{ time: string; value: number }>>([]);
  const [showFullLogs, setShowFullLogs] = useState(false);

  // 应用初始化信息
  useEffect(() => {
    log('调试页面初始化中...');
    gatherAppInfo();
    checkHealth();
    checkConfigStatus();

    // 定期刷新状态
    const interval = setInterval(() => {
      checkHealth();
      checkConfigStatus();
    }, 30000); // 每30秒刷新一次

    return () => clearInterval(interval);
  }, []);

  // 收集应用信息
  const gatherAppInfo = () => {
    try {
      const info = {
        appName: '三国风云对话',
        version: '1.0.0',
        environment: process.env.NODE_ENV || 'development',
        nodeVersion: typeof window !== 'undefined' ? navigator.userAgent : 'Server-side',
        browser: typeof window !== 'undefined' ? navigator.appName : 'Unknown',
        theme: theme,
        timestamp: new Date().toLocaleString(),
      };
      setAppInfo(info);
      log('应用信息收集完成');
    } catch (error) {
      log(`收集应用信息失败: ${error}`);
    }
  };

  // 检查后端健康状态
  const checkHealth = async () => {
    try {
      log('检查后端服务健康状态...');
      const startTime = performance.now();
      const response = await fetch('http://localhost:5000/api/health', {
        timeout: 5000
      });
      const endTime = performance.now();

      if (response.ok) {
        const data = await response.json();
        setHealthStatus(data);

        // 添加性能数据
        const newPerfData = [...performanceData];
        newPerfData.push({
          time: new Date().toLocaleTimeString(),
          value: Math.round(endTime - startTime)
        });

        // 只保留最近10个数据点
        if (newPerfData.length > 10) {
          newPerfData.shift();
        }
        setPerformanceData(newPerfData);

        log('后端服务健康检查通过');
      } else {
        setHealthStatus({ status: 'error', message: `请求失败: ${response.status} ${response.statusText}` });
        log(`后端服务健康检查失败: ${response.status} ${response.statusText}`);
      }
    } catch (error: any) {
      setHealthStatus({ status: 'error', message: error.message });
      log(`后端服务健康检查异常: ${error.message}`);
    }
  };

  // 检查配置状态
  const checkConfigStatus = async () => {
    try {
      log('检查API配置状态...');
      const timestamp = new Date().getTime();
      const response = await fetch(`http://localhost:5000/api/config/status?t=${timestamp}`, {
        timeout: 5000
      });

      if (response.ok) {
        const data = await response.json();
        setConfigStatus(data);
        log('API配置状态检查完成');
      } else {
        setConfigStatus({ error: `请求失败: ${response.status} ${response.statusText}` });
        log(`API配置状态检查失败: ${response.status} ${response.statusText}`);
      }
    } catch (error: any) {
      setConfigStatus({ error: error.message });
      log(`API配置状态检查异常: ${error.message}`);
    }
  };

  // 测试API调用
  const testApiCall = async () => {
    if (!apiTestMessage.trim()) {
      toast.error('请输入测试消息');
      return;
    }

    setIsTesting(true);
    setApiResponse('');
    setApiError('');
    log(`开始测试API调用: 人物=${selectedCharacter}, 消息=${apiTestMessage}`);

    try {
      const startTime = performance.now();
      const response = await fetch('http://localhost:5000/api/chat/message', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          character: selectedCharacter,
          userMessage: apiTestMessage
        }),
        timeout: 10000
      });
      const endTime = performance.now();

      const responseText = await response.text();
      log(`API调用完成，耗时: ${Math.round(endTime - startTime)}ms, 状态码: ${response.status}`);

      if (response.ok) {
        try {
          const data = JSON.parse(responseText);
          setApiResponse(JSON.stringify(data, null, 2));
          if (data.success) {
            toast.success('API调用成功');
          } else {
            toast.warning('API返回了失败状态');
          }
        } catch (jsonError) {
          setApiResponse(responseText);
          setApiError(`JSON解析错误: ${jsonError.message}`);
          toast.error('API返回格式错误');
        }
      } else {
        setApiResponse(responseText);
        setApiError(`请求失败: ${response.status} ${response.statusText}`);
        toast.error('API调用失败');
      }
    } catch (error: any) {
      setApiError(error.message);
      log(`API调用异常: ${error.message}`);
      toast.error(`API调用异常: ${error.message}`);
    } finally {
      setIsTesting(false);
    }
  };

  // 日志记录函数
  const log = (message: string) => {
    const timestamp = new Date().toLocaleTimeString();
    const logMessage = `[${timestamp}] ${message}`;
    setLogs(prev => [...prev, logMessage]);
  };

  // 清除日志
  const clearLogs = () => {
    setLogs([]);
    log('日志已清除');
  };

  // 复制到剪贴板
  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text).then(() => {
      toast.success('已复制到剪贴板');
    }).catch(() => {
      toast.error('复制失败');
    });
  };

  return (
      <div className={`min-h-screen ${isDark ? 'dark bg-gray-900 text-gray-100' : 'bg-gray-50 text-gray-900'} p-4 transition-colors duration-300`}>
        <header className="mb-6">
          <div className="flex justify-between items-center mb-2">
            <h1 className="text-2xl font-bold flex items-center">
              <Code className="mr-2" /> 调试中心
            </h1>
            <div className="flex gap-2">
              <button
                  onClick={checkHealth}
                  className="p-2 rounded-lg bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-200 hover:bg-blue-200 dark:hover:bg-blue-800 transition-colors"
                  aria-label="Refresh health"
              >
                <RefreshCcw size={18} />
              </button>
            </div>
          </div>
          <p className="text-sm text-gray-500 dark:text-gray-400">
            监控应用状态，测试API调用，查看详细日志
          </p>
        </header>

        <main className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* 左侧面板：应用信息和状态 */}
          <div className="lg:col-span-1 space-y-6">
            {/* 应用基本信息 */}
            <div className="bg-white dark:bg-gray-800 rounded-xl p-5 shadow-sm border border-gray-200 dark:border-gray-700">
              <div className="flex items-center mb-4">
                <Info className="text-blue-500 mr-2" size={20} />
                <h2 className="text-lg font-semibold">应用信息</h2>
              </div>
              <div className="space-y-3">
                {Object.entries(appInfo).map(([key, value]) => (
                    <div key={key} className="flex justify-between text-sm">
                      <span className="text-gray-500 dark:text-gray-400 capitalize">{key.replace(/([A-Z])/g, ' $1').trim()}</span>
                      <span className="font-mono">{value}</span>
                    </div>
                ))}
              </div>
            </div>

            {/* 后端健康状态 */}
            <div className="bg-white dark:bg-gray-800 rounded-xl p-5 shadow-sm border border-gray-200 dark:border-gray-700">
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center">
                  <Server className={`mr-2 ${healthStatus.status === 'ok' ? 'text-green-500' : 'text-red-500'}`} size={20} />
                  <h2 className="text-lg font-semibold">后端服务状态</h2>
                </div>
                <span className={`px-2 py-1 text-xs rounded-full ${
                    healthStatus.status === 'ok'
                        ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
                        : 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200'
                }`}>
                {healthStatus.status === 'ok' ? '正常' : '异常'}
              </span>
              </div>

              {healthStatus.status === 'ok' ? (
                  <div className="space-y-3 text-sm">
                    <div className="flex justify-between">
                      <span className="text-gray-500 dark:text-gray-400">消息</span>
                      <span>{healthStatus.message}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-500 dark:text-gray-400">时间戳</span>
                      <span>{new Date(healthStatus.timestamp).toLocaleString()}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-500 dark:text-gray-400">Node.js版本</span>
                      <span className="font-mono">{healthStatus.nodeVersion}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-500 dark:text-gray-400">环境变量</span>
                      <span>{healthStatus.envLoaded ? '已加载' : '未加载'}</span>
                    </div>
                  </div>
              ) : (
                  <div className="text-sm text-red-500 dark:text-red-400">
                    <AlertTriangle size={16} className="inline mr-1" />
                    {healthStatus.message || '后端服务不可用'}
                    <p className="mt-2 text-gray-500 dark:text-gray-400">
                      建议运行: npm run dev:server-vanilla
                    </p>
                  </div>
              )}

              {/* 性能图表 */}
              {healthStatus.status === 'ok' && performanceData.length > 1 && (
                  <div className="mt-4">
                    <h3 className="text-sm font-medium mb-2 text-gray-500 dark:text-gray-400">响应时间 (ms)</h3>
                    <ResponsiveContainer width="100%" height={80}>
                      <LineChart data={performanceData}>
                        <CartesianGrid strokeDasharray="3 3" vertical={false} stroke={isDark ? '#374151' : '#e5e7eb'} />
                        <XAxis
                            dataKey="time"
                            tick={{ fontSize: 10 }}
                            axisLine={false}
                            tickLine={false}
                        />
                        <YAxis
                            tick={{ fontSize: 10 }}
                            axisLine={false}
                            tickLine={false}
                        />
                        <Tooltip
                            contentStyle={{
                              backgroundColor: isDark ? '#1f2937' : 'white',
                              border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`,
                              borderRadius: '6px',
                              fontSize: '12px'
                            }}
                        />
                        <Line
                            type="monotone"
                            dataKey="value"
                            stroke="#3b82f6"
                            strokeWidth={2}
                            dot={{ r: 3 }}
                            activeDot={{ r: 5 }}
                        />
                      </LineChart>
                    </ResponsiveContainer>
                  </div>
              )}
            </div>

            {/* API配置状态 */}
            <div className="bg-white dark:bg-gray-800 rounded-xl p-5 shadow-sm border border-gray-200 dark:border-gray-700">
              <div className="flex items-center mb-4">
                <Settings className="text-purple-500 mr-2" size={20} />
                <h2 className="text-lg font-semibold">API配置状态</h2>
              </div>

              {configStatus.error ? (
                  <div className="text-sm text-red-500 dark:text-red-400">
                    <AlertTriangle size={16} className="inline mr-1" />
                    {configStatus.error}
                  </div>
              ) : (
                  <div className="space-y-4">
                    <div className="text-sm">
                      <div className="flex justify-between mb-1">
                        <span className="text-gray-500 dark:text-gray-400">API密钥配置</span>
                        <span className={`${
                            configStatus.hasApiKeys
                                ? 'text-green-500'
                                : 'text-amber-500'
                        }`}>
                      {configStatus.hasApiKeys ? '已配置' : '未配置'}
                    </span>
                      </div>

                      {/* 各个密钥的状态 */}
                      <div className="grid grid-cols-2 gap-2 mt-2 text-xs">
                        {Object.entries(configStatus.keyStatus || {}).map(([key, status]) => (
                            <div key={key} className="flex items-center">
                              <span className="capitalize mr-1">{key.replace(/([A-Z])/g, ' $1').trim()}</span>
                              <span className={`ml-1 ${
                                  status === 'configured'
                                      ? 'text-green-500'
                                      : 'text-gray-500'
                              }`}>
                          {status === 'configured' ? <Check size={12} /> : <X size={12} />}
                        </span>
                            </div>
                        ))}
                      </div>
                    </div>

                    <div className="text-sm">
                      <div className="flex justify-between">
                        <span className="text-gray-500 dark:text-gray-400">API基础URL</span>
                        <span className={configStatus.hasValidBaseUrl ? 'text-green-500' : 'text-amber-500'}>
                      {configStatus.hasValidBaseUrl ? '有效' : '默认'}
                    </span>
                      </div>
                      <div className="font-mono text-xs mt-1 truncate" title={configStatus.apiBaseUrl}>
                        {configStatus.apiBaseUrl || '未配置'}
                      </div>
                    </div>

                    <div className="text-xs text-gray-500 dark:text-gray-400">
                      最后检查时间: {new Date(configStatus.lastChecked || Date.now()).toLocaleTimeString()}
                    </div>
                  </div>
              )}
            </div>
          </div>

          {/* 右侧面板：API测试和日志 */}
          <div className="lg:col-span-2 space-y-6">
            {/* API测试工具 */}
            <div className="bg-white dark:bg-gray-800 rounded-xl p-5 shadow-sm border border-gray-200 dark:border-gray-700">
              <div className="flex items-center mb-4">
                <Terminal className="text-green-500 mr-2" size={20} />
                <h2 className="text-lg font-semibold">API测试工具</h2>
              </div>

              <div className="space-y-4">
                {/* 人物选择 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    选择历史人物
                  </label>
                  <select
                      value={selectedCharacter}
                      onChange={(e) => setSelectedCharacter(e.target.value as Character)}
                      className="w-full px-3 py-2 bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="liuBei">刘备</option>
                    <option value="caoCao">曹操</option>
                    <option value="sunQuan">孙权</option>
                  </select>
                </div>

                {/* 消息输入 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    测试消息
                  </label>
                  <textarea
                      value={apiTestMessage}
                      onChange={(e) => setApiTestMessage(e.target.value)}
                      placeholder="请输入要发送的消息..."
                      rows={3}
                      className="w-full px-3 py-2 bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>

                {/* 测试按钮 */}
                <button
                    onClick={testApiCall}
                    disabled={isTesting || !apiTestMessage.trim()}
                    className={`w-full py-2 px-4 flex items-center justify-center rounded-lg ${
                        isTesting
                            ? 'bg-gray-300 dark:bg-gray-600 text-gray-500 dark:text-gray-400 cursor-not-allowed'
                            : 'bg-blue-600 text-white hover:bg-blue-700 dark:bg-blue-700 dark:hover:bg-blue-800 transition-colors'
                    }`}
                >
                  {isTesting ? (
                      <>
                        <RefreshCcw size={16} className="mr-2 animate-spin" /> 测试中...
                      </>
                  ) : (
                      <>
                        <Send size={16} className="mr-2" /> 发送测试请求
                      </>
                  )}
                </button>
              </div>

              {/* API响应展示 */}
              {apiResponse || apiError ? (
                  <div className="mt-6">
                    <h3 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      API {apiError ? '错误' : '响应'}
                    </h3>
                    <div className={`bg-gray-900 text-gray-100 p-4 rounded-lg text-xs font-mono max-h-64 overflow-y-auto ${
                        apiError ? 'border-l-4 border-red-500' : 'border-l-4 border-green-500'
                    }`}>
                      <pre>{apiError || apiResponse}</pre>
                    </div>
                    <div className="flex justify-end mt-2">
                      <button
                          onClick={() => copyToClipboard(apiError || apiResponse)}
                          className="text-xs text-blue-500 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300"
                      >
                        复制
                      </button>
                    </div>
                  </div>
              ) : null}
            </div>

            {/* 日志面板 */}
            <div className="bg-white dark:bg-gray-800 rounded-xl p-5 shadow-sm border border-gray-200 dark:border-gray-700">
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center">
                  <Terminal className="text-gray-500 mr-2" size={20} />
                  <h2 className="text-lg font-semibold">系统日志</h2>
                </div>
                <div className="flex gap-2">
                  <button
                      onClick={() => setShowFullLogs(!showFullLogs)}
                      className="text-sm px-2 py-1 rounded bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
                  >
                    {showFullLogs ? '精简视图' : '完整视图'}
                  </button>
                  <button
                      onClick={clearLogs}
                      className="text-sm px-2 py-1 rounded bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-300 hover:bg-red-200 dark:hover:bg-red-800 transition-colors"
                  >
                    清空日志
                  </button>
                </div>
              </div>

              <div className="bg-gray-900 text-gray-100 p-4 rounded-lg text-xs font-mono max-h-96 overflow-y-auto">
                {logs.length === 0 ? (
                    <div className="text-gray-500">暂无日志记录</div>
                ) : (
                    <div className="space-y-1">
                      {logs.slice(showFullLogs ? 0 : -20).map((log, index) => (
                          <div key={index} className={
                            log.includes('error') || log.includes('失败') || log.includes('异常')
                                ? 'text-red-400'
                                : log.includes('success') || log.includes('通过')
                                    ? 'text-green-400'
                                    : log.includes('检查') || log.includes('测试')
                                        ? 'text-blue-400'
                                        : 'text-gray-300'
                          }>
                            {log}
                          </div>
                      ))}
                    </div>
                )}
              </div>

              {logs.length > 20 && !showFullLogs && (
                  <div className="text-center text-xs text-gray-500 dark:text-gray-400 mt-2">
                    显示最近20条日志，共 {logs.length} 条
                  </div>
              )}
            </div>
          </div>
        </main>

        <footer className="mt-8 text-center text-sm text-gray-500 dark:text-gray-400">
          <p>调试工具仅供开发使用 · {new Date().toLocaleDateString()}</p>
        </footer>
      </div>
  );
}